<template>
  <div class="mini_box" id="mini_box" v-drag>
    <transition name="fade">
      <div class="playlist" v-if="playList" :style="myStyle">
        <my-scroll :opacity="0.5">
          <div v-for="(item, index) in getMusicList" :key="index" class="item">
            <span class="gif" v-if="getIndex == index">
              <img src="/images/dh.gif" alt />
            </span>
            <span
              class="name"
              :class="getIndex == index ? 'active_color' : ''"
              @click="playSong(index)"
            >{{ item.name }}</span>
            <span class="el-icon-delete delete" @click="deleteSong(index)"></span>
          </div>
        </my-scroll>
      </div>
    </transition>
    <div class="bottom_box">
      <div class="imgbox" @click="golyrics">
        <img :src="getImgUrl" alt />
        <div class="mask"></div>
      </div>
      <div class="switch_box">
        <div class="info">
          <div class="name">{{ getName }}</div>
          <div class="lyrics">
            <my-scroll ref="mini_scroll" :opacity="0">
              <ul>
                <li v-for="(item, index) in val" :key="index">{{ item[1] }}</li>
              </ul>
            </my-scroll>
          </div>
        </div>
        <div class="control">
          <div>
            <i @click="prevSong" class="iconfont icon-shangyishou"></i>
          </div>
          <div class="play_pause" @click="play_pause">
            <i v-if="!getState" class="iconfont icon-bofang"></i>
            <i v-else class="iconfont icon-tingzhi"></i>
          </div>
          <div>
            <i @click="nextSong" class="iconfont icon-xiayishou"></i>
          </div>
        </div>
      </div>
      <div class="other">
        <div class="screen" @click="goMusic">
          <span class="iconfont icon-baseline-library_mus"></span>
        </div>
        <!-- <div class="model" @click="changeModel">
          <i v-if="getModel == 0" class="iconfont icon-xunhuan"></i>
          <i v-else-if="getModel == 1" class="iconfont icon-xunhuan1"></i>
          <i v-else-if="getModel == 2" class="iconfont icon-suiji"></i>
        </div>-->
        <div class="switch" @click="showPlayList">
          <span class="iconfont icon-bofangliebiao"></span>
        </div>
      </div>
    </div>
    <audio id="myaudio" :src="getMusicUrl"></audio>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      currentIndex: 0,
      lyric: '',
      duration: 0,
      scrolltop: 0,
      val: null,
      div_width: 0,
      div_height: 0,
      audio: null,
      playList: false,
      screen_width: 0,
      screen_height: 0,
      myStyle: {}
    }
  },
  computed: {
    // vue辅助函数
    ...mapGetters([
      'getName',
      'getAuthor',
      'getMusicUrl',
      'getImgUrl',
      'getIndex',
      'getModel',
      'getMusicList',
      'getState',
      'getLyrics',
      'getCurrentTime',
      'getLyricsIndex',
      'getCanPlay'
    ])
  },
  watch: {
    getLyricsIndex: function (newValue, oldValue) {
      if (newValue == 0) {
        this.scrolltop = 0
      }
      if (newValue >= 1) {
        this.scrolltop = newValue * 25
      }
      this.$refs.mini_scroll.$refs.vs.scrollTo({
        y: this.scrolltop
      })
    },
    // 监听歌曲是否可以播放，弹出提示框
    getCanPlay: function () {
      if (this.getCanPlay) {
        this.$message({
          message: this.getName + '--' + this.getAuthor,
          type: 'success',
          center: true
        })
      }
    }
  },
  directives: {
    drag: {
      // 指令的定义
      bind: (el) => {
        let odiv = el //获取当前元素
        let screen_width = document.body.clientWidth
        let screen_height = document.body.clientHeight
        odiv.onmousedown = (e) => {
          // 获取元素的宽高
          let div_width = odiv.getBoundingClientRect().width
          let div_height = odiv.getBoundingClientRect().height

          // 可拖动的最大 top 和 left 值
          let max_left = screen_width - div_width
          let max_top = screen_height - div_height

          //算出鼠标相对元素的位置
          let disX = e.clientX - odiv.offsetLeft
          let disY = e.clientY - odiv.offsetTop

          document.onmousemove = (e) => {
            //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
            let left = e.clientX - disX
            let top = e.clientY - disY

            // 限定移动区域
            if (left < 0) {
              left = 0
            }
            if (left > max_left) {
              left = max_left
            }
            if (top < 0) {
              top = 0
            }
            if (top > max_top) {
              top = max_top
            }

            //移动当前元素
            odiv.style.left = left + 'px'
            odiv.style.top = top + 'px'
          }
          document.onmouseup = (e) => {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    }
  },
  created() {
    // 由mutations.js的代码触发（本地没有播放列表时，点击播放按钮）
    this.$EventBus.$on('goMusic', () => {
      this.$router.push('/musichome')
    })
  },
  mounted() {
    this.screen_width = document.body.clientWidth
    this.screen_height = document.body.clientHeight

    this.$store.commit('getAudio')
    var audio = document.getElementById('myaudio')
    this.audio = audio

    //监听音频是否可以开始播放
    audio.addEventListener('canplay', () => {
      if (audio.paused) {
        this.val = [[0, this.getAuthor]]
      }
      this.$store.commit('listenLyrics')
      this.$store.commit('upDateStatus', this.$store.state.song.songName)
      this.duration = audio.duration
      this.$store.commit('updateDuration', audio.duration)
      this.$store.commit('changeCanPlay', true)
    })

    // 监听歌曲是否已经播放结束
    audio.addEventListener('ended', () => {
      if (this.getModel == 1) {
        //当播放模式是循环时
        audio.load()
        audio.setAttribute('autoplay', 'autoplay')
      } else {
        // this.$store.commit("changeCanPlay", false)
        this.$store.commit('next')
      }
    })

    //获取link（ico）标签（为了修改成歌曲的图片）
    var links = document.getElementsByTagName('link')[0]
    audio.addEventListener('play', () => {
      document.title = this.getName
      links.setAttribute('href', this.getImgUrl)
      this.val = this.getLyrics
    })
    audio.addEventListener('pause', () => {
      document.title = '深的个人博客'
      links.setAttribute('href', '/logo.ico')
      this.val = [[0, this.getAuthor]]
    })
  },
  methods: {
    // 显示隐藏播放列表
    showPlayList(e) {
      let div_clientY = e.clientY
      if (this.screen_height / 2 > div_clientY) {
        this.myStyle = {
          top: '50px',
          boxShadow: '0px 20px 40px -15px rgba(0, 0, 0, 0.2)'
        }
      } else {
        this.myStyle = {
          bottom: '50px',
          boxShadow: '0px -20px 50px -15px rgba(0, 0, 0, 0.2)'
        }
      }

      this.playList = !this.playList
    },
    // 点击播放暂停
    play_pause() {
      this.$store.commit('play_pause')
    },
    // 上一首
    prevSong() {
      this.$store.commit('prev')
    },

    // 下一首
    nextSong() {
      this.$store.commit('next')
    },

    // 去音乐界面
    goMusic() {
      this.$router.push('/musichome')
    },

    // 跳转到歌词页
    golyrics() {
      if (this.getMusicUrl == '') {
        this.$router.push('/musichome')
        this.$notify({
          title: '警告',
          message: '暂无播放列表,请在音乐库里选择要播放的音乐',
          type: 'warning'
        })
      } else {
        let screenWidth = document.body.clientWidth
        if (screenWidth <= 600) {
          //移动端
          this.$EventBus.$emit('changeShowPlay') //更改App.vue页面Play组件的状态
        }
      }
    },

    // 点击播放列表
    playSong(index) {
      this.$store.commit('upDateIndex', index)
    },

    //删除播放列表里的歌曲
    deleteSong(index) {
      this.$store.commit('delete', index)
    },

    // 点击更换播放模式
    changeModel() {
      let model = this.getModel + 1
      if (model > 2) {
        model = 0
      }
      this.$store.commit('changeModel', model)
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../scss/common.scss';
@import './miniplay.scss';
</style>
